package com.meixiang.activity.account.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.SelectMemberStoreActivity;
import com.meixiang.entity.account.UserInfo;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.main.MainActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.util.DesUtil;
import com.meixiang.view.ClearEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 登录
 *
 * @author zys
 */
public class LoginActivity extends BaseActivity implements PlatformActionListener,Handler.Callback {
    /**
     * 手机号、邮箱
     */
    @Bind(R.id.cet_input_name)
    ClearEditText cet_input_name;
    /**
     * 密码
     */
    @Bind(R.id.cet_input_pwd)
    ClearEditText cet_input_pwd;
    /**
     * 登录按钮
     */
    @Bind(R.id.tv_login)
    TextView tv_login;
    /**
     * 忘记密码
     */
    @Bind(R.id.tv_forget_pwd)
    TextView tv_forget_pwd;
    /**
     * 注册账户
     */
    @Bind(R.id.tv_reg_account)
    TextView tv_reg_account;

    private Activity mActivity;
    //融云token
    private String token;

    private UserInfo mUserInfo;

    /**
     * QQ登录按钮
     */
    @Bind(R.id.iv_qq)
    ImageView iv_qq;

    /**
     * 微信登录按钮
     */
    @Bind(R.id.iv_weixin)
    ImageView iv_weixin;


    private String codeStr;




    private static final int MSG_SMSSDK_CALLBACK = 1;
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR= 3;
    private static final int MSG_AUTH_COMPLETE = 4;

    private String smssdkAppkey;
    private String smssdkAppSecret;

    private Handler handler;


    private String platformStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);

        //杨德成 20160909 ShareSDK
        ShareSDK.initSDK(this);

        ButterKnife.bind(this);
        mActivity = LoginActivity.this;
        super.onCreate(savedInstanceState);

        // 初始化ui
        handler = new Handler(this);

    }

    @Override
    protected void initTitle() {
        setRightTitle("登录", "注册", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, RegisterActivity.class));
            }
        });

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void setData() {
    }

    @OnClick({R.id.tv_login, R.id.tv_forget_pwd, R.id.tv_reg_account,R.id.iv_qq,R.id.iv_weixin})
    public void onClick(View view) {
        if(Tool.isFastDoubleClick()){
            return;
        }
        switch (view.getId()) {

            case R.id.tv_login:
                if (TextUtils.isEmpty(cet_input_name.getText().toString())) {
                    Tool.showTextToast(mActivity, "请输入手机号码");
                    return;
                }
                if (cet_input_pwd.getText().length() < 6 || cet_input_pwd.getText().length() > 16) {
                    Tool.showTextToast(mActivity, "请输入6~16位的密码");
                    return;
                }
                sendHttp();
                break;
            case R.id.tv_forget_pwd:
                startActivity(new Intent(context, ForgetPasswordActivity.class));
                break;
            case R.id.tv_reg_account:
                startActivity(new Intent(context, RegisterActivity.class));
                break;
            case  R.id.iv_qq:
                //QQ空间

                platformStr="QQ";
                Platform qzone = ShareSDK.getPlatform(QZone.NAME);
                authorize(qzone);


                break;

            case  R.id. iv_weixin:
                //微信登录
                //测试时，需要打包签名；sample测试时，用项目里面的demokey.keystore
                //打包签名apk,然后才能产生微信的登录

                platformStr="微信";
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                authorize(wechat);
                break;

        }
    }


    /**
     * 登录
     */
    private void sendHttp() {
//        password	String	必填			密码
//        username	String	必填			用户名
        HttpParams params = new HttpParams();
        params.put("username", cet_input_name.getText().toString().trim());
        params.put("password", DesUtil.md5(cet_input_pwd.getText().toString().trim()));
        HttpUtils.post(Config.LOGIN, params, new HttpCallBack(mActivity,"正在登录中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                HashMap<String, String> vals = new HashMap<String, String>();
                vals.put("jsessionid", result.optString("sessionId"));
                MXApplication.mApp.getSession().set(vals);
                AbToastUtil.showToast(LoginActivity.this, message);

                if (result.optInt("memberCardNum") > 1) {
                    startActivity(new Intent(context, SelectMemberStoreActivity.class));
                } else {
                    getUserinfo();
                    startActivity(MainActivity.class);
                }
                finish();
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(LoginActivity.this, message);
            }
        });


    }

    /**
     * 登录成功获取用户信息保存并且用户信息
     */
    private void getUserinfo() {
        HttpParams params = new HttpParams();

        HttpUtils.post(Config.USERINFO_URL, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                mUserInfo = AbJsonUtil.fromJson(result.toString(), UserInfo.class);
                MXApplication.mApp.setUser(mUserInfo);

                Log.e("TAG", "得到当前用户信息==" + MXApplication.mApp.getUser());

            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(activity, message);
            }
        });

    }


    //杨德成 20160909 第三方登录授权
    private void authorize(Platform plat) {
        if (plat == null) {
            //popupOthers();
            return;
        }

        plat.setPlatformActionListener(this);
        //关闭SSO授权
        plat.SSOSetting(true);
        plat.showUser(null);
    }

    //start  杨德成 20160909 一下三个为ShareSDK回调返回
    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {

        if (action == Platform.ACTION_USER_INFOR) {

            codeStr=action+"";

            Message msg = new Message();
            msg.what = MSG_AUTH_COMPLETE;
            msg.obj = new Object[] {platform.getName(), res};
            handler.sendMessage(msg);
        }

    }

    @Override
    public void onError(Platform platform, int action, Throwable t) {
        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        t.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int action) {
        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_CANCEL);
        }
    }



    @SuppressWarnings("unchecked")
    public boolean handleMessage(Message msg) {
        switch(msg.what) {
            case MSG_AUTH_CANCEL: {
                //取消授权
                Toast.makeText(activity, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
            } break;
            case MSG_AUTH_ERROR: {
                //授权失败
                Toast.makeText(activity, R.string.auth_error, Toast.LENGTH_SHORT).show();
            } break;
            case MSG_AUTH_COMPLETE: {
                //授权成功
                Toast.makeText(activity, R.string.auth_complete, Toast.LENGTH_SHORT).show();
                Object[] objs = (Object[]) msg.obj;
                String platform = (String) objs[0];

                //ydc s
                Platform ptf = ShareSDK.getPlatform( platform);
                String userToken=ptf.getDb().getToken();
                String UserName=ptf.getDb().getUserName();
                //ydc d
                HashMap<String, Object> res = (HashMap<String, Object>) objs[1];
                /*if (signupListener != null && signupListener.onSignin(platform, res)) {
                    SignupPage signupPage = new SignupPage();
                    signupPage.setOnLoginListener(signupListener);
                    signupPage.setPlatform(platform);
                    signupPage.show(activity, null);
                }*/

               /* Toast.makeText(activity, "等等后台接入", Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(LoginActivity.this,BindingAccountActivity.class);
                intent.putExtra("username",UserName);
                startActivity(intent);*/

                thirdLongin(userToken,UserName,platform );



            } break;
            case MSG_SMSSDK_CALLBACK: {/*
                if (msg.arg2 == SMSSDK.RESULT_ERROR) {
                    Toast.makeText(activity, "操作失败", Toast.LENGTH_SHORT).show();
                } else {
                    switch (msg.arg1) {
                        case SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE: {
                            if(msgLoginDlg != null && msgLoginDlg.isShowing()){
                                msgLoginDlg.dismiss();
                            }
                            Toast.makeText(activity, "提交验证码成功", Toast.LENGTH_SHORT).show();
                            Message m = new Message();
                            m.what = MSG_AUTH_COMPLETE;
                            m.obj = new Object[] {"SMSSDK", (HashMap<String, Object>) msg.obj};
                            handler.sendMessage(m);
                        } break;
                        case SMSSDK.EVENT_GET_VERIFICATION_CODE:{
                            Toast.makeText(activity, "验证码已经发送", Toast.LENGTH_SHORT).show();
                        } break;
                    }
                }*/
            }
            break;
        }
        return false;
    }

    //end  杨德成 20160909 一下三个为ShareSDK回调返回


    /**
     * yangdecheng 第三方登录请求,未调试(临时地址暂时配置此处)
     */
    private void thirdLongin(String token,final String UserName,String platform ) {

        String urlStr="";
        if(platform.equals("QZone")){
           // urlStr="http://192.168.0.21:8080/maxmind-api/thirdlogin/qqUserInfo";
            urlStr=Config.qqUserInfo_URL;
        }else{
            //urlStr="http://192.168.0.21:8080/maxmind-api/thirdlogin/weixinUserInfo";
            urlStr=Config.weixinUserInfo_URL;
        }
        HttpParams params = new HttpParams();
        //params.put("code", code);
        params.put("access_token", token);
        HttpUtils.post(urlStr, params, new HttpCallBack(mActivity,"正在登录中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                String openid = result.optString("openid");
                String codeStr= result.optString("code");
                //-1：登录信息保存失败；0：已绑定；1：未绑定
                if(codeStr.equals("1")){
                    Intent intent=new Intent(LoginActivity.this,BindingAccountActivity.class);
                    intent.putExtra("openid",openid);
                    intent.putExtra("username",UserName);
                    intent.putExtra("platformStr",platformStr);

                    startActivity(intent);
                }else if(codeStr.equals("0")){

                    String sessionId=result.optString("sessionId");
                    String memberCardNum= result.optString("memberCardNum");
                    HashMap<String, String> vals = new HashMap<String, String>();
                    vals.put("jsessionid", sessionId);
                    MXApplication.mApp.getSession().set(vals);
                    AbToastUtil.showToast(LoginActivity.this, message);

                    if (Integer.parseInt(memberCardNum) > 1) {
                        startActivity(new Intent(context, SelectMemberStoreActivity.class));
                    } else {
                        getUserinfo();
                        startActivity(MainActivity.class);
                    }
                    finish();
                }
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(LoginActivity.this, message);

            }
        });


    }

}
